package cn.lili.controller.store;

import cn.lili.common.enums.ResultCode;
import cn.lili.common.enums.ResultUtil;
import cn.lili.common.security.AuthUser;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.security.token.Token;
import cn.lili.common.utils.CurrencyUtil;
import cn.lili.common.utils.ObjectUtil;
import cn.lili.common.utils.OcrBusinessLicense;
import cn.lili.common.utils.OcrIdcard;
import cn.lili.common.vo.PageVO;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.connect.entity.dto.AuthToken;
import cn.lili.modules.goods.entity.vos.StoreGoodsLabelVO;
import cn.lili.modules.goods.service.StoreGoodsLabelService;
import cn.lili.modules.member.entity.dos.Member;
import cn.lili.modules.member.entity.dto.MemberEvaluationDTO;
import cn.lili.modules.member.entity.vo.GradeLevelVO;
import cn.lili.modules.member.service.MemberService;
import cn.lili.modules.member.service.StoreLogisticsService;
import cn.lili.modules.order.order.entity.dos.Order;
import cn.lili.modules.order.order.entity.dto.OrderSearchParams;
import cn.lili.modules.order.order.entity.enums.OrderStatusEnum;
import cn.lili.modules.order.order.entity.enums.OrderTypeEnum;
import cn.lili.modules.order.order.entity.vo.OrderSimpleVO;
import cn.lili.modules.order.order.entity.vo.OrderVO;
import cn.lili.modules.order.order.service.OrderService;
import cn.lili.modules.store.entity.dos.Store;
import cn.lili.modules.store.entity.dos.StoreEvaluation;
import cn.lili.modules.store.entity.dto.*;
import cn.lili.modules.store.entity.enums.StoreStatusEnum;
import cn.lili.modules.store.entity.vos.*;
import cn.lili.modules.store.service.StoreDetailService;
import cn.lili.modules.store.service.StoreEvaluationService;
import cn.lili.modules.store.service.StoreService;
import cn.lili.modules.system.entity.vo.StoreLogisticsVO;
import cn.lili.modules.wallet.entity.dos.WalletDetail;
import cn.lili.modules.wallet.entity.dos.WalletLogDetail;
import cn.lili.modules.wallet.entity.enums.DepositServiceTypeEnum;
import cn.lili.modules.wallet.entity.enums.WalletOwnerEnum;
import cn.lili.modules.wallet.entity.vo.WalletDetailVO;
import cn.lili.modules.wallet.entity.vo.WalletLogDetailVO;
import cn.lili.modules.wallet.service.WalletDetailService;
import cn.lili.modules.wallet.service.WalletLogDetailService;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.ocr20191230.models.RecognizeBusinessLicenseRequest;
import com.aliyun.ocr20191230.models.RecognizeBusinessLicenseResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 买家端,店铺接口
 *
 * @author Bulbasaur
 * @since 2020/11/17 2:32 下午
 */
@RestController
@RequestMapping("/buyer/store")
@Api(tags = "买家端,店铺接口")
public class StoreBuyerController {

	/**
	 * 店铺
	 */
	@Autowired
	private StoreService storeService;
	/**
	 * 店铺商品分类
	 */
	@Autowired
	private StoreGoodsLabelService storeGoodsLabelService;
	/**
	 * 店铺详情
	 */
	@Autowired
	private StoreDetailService storeDetailService;

	/**
	 * 订单
	 */
	@Autowired
	private OrderService orderService;

	@Autowired
	private WalletDetailService walletDetailService;
	@Autowired
	private MemberService memberService;

	/**
	 * 物流公司
	 */
	@Autowired
	private StoreLogisticsService storeLogisticsService;

	// 商品店铺
	@Autowired
	private StoreEvaluationService storeEvaluationService;

	@ApiOperation(value = "获取店铺列表分页")
	@GetMapping
	public ResultMessage<IPage<StoreVO>> getByPage(StoreSearchParams entity, PageVO page) {
		return ResultUtil.data(storeService.findByConditionPage(entity, page));
	}

	@ApiOperation(value = "通过id获取店铺信息")
	@ApiImplicitParam(name = "id", value = "店铺ID", required = true, paramType = "path")
	@RequestMapping(value = "/get/detail/{id}")
	public ResultMessage<StoreBasicInfoVO> detail(@NotNull @PathVariable String id, String trapeze) {
		return ResultUtil.data(storeDetailService.getStoreBasicInfoDTO(id, trapeze));
	}

	@ApiOperation(value = "通过会员id获取店铺信息")
	@ApiImplicitParam(name = "id", value = "店铺ID", required = true, paramType = "path")
	@RequestMapping(value = "/get/detail")
	public ResultMessage<Store> detailByMember() {
		Store store = new Store();
		AuthUser currentUser = UserContext.getCurrentUser();
		if (ObjectUtils.isNotEmpty(currentUser)) {
			store = storeService.getOne(new QueryWrapper<Store>().eq("member_id", currentUser.getId())
					.eq("store_disable", StoreStatusEnum.OPEN.name()));
		}
		return ResultUtil.data(store);
	}

	@ApiOperation(value = "修改店铺信息")
	@ApiImplicitParam(name = "id", value = "店铺ID", required = true, paramType = "path")
	@RequestMapping(value = "/get/updateInfo")
	public ResultMessage<Boolean> updateInfo(Store store) {

		return ResultUtil.data(storeService.updateById(store));
	}

	@ApiOperation(value = "通过id获取店铺详细信息-营业执照")
	@ApiImplicitParam(name = "id", value = "店铺ID", required = true, paramType = "path")
	@RequestMapping(value = "/get/licencePhoto/{id}")
	public ResultMessage<StoreOtherVO> licencePhoto(@NotNull @PathVariable String id) {
		return ResultUtil.data(storeDetailService.getStoreOtherVO(id));
	}

	@ApiOperation(value = "通过id获取店铺商品分类")
	@ApiImplicitParams({@ApiImplicitParam(name = "id", value = "店铺ID", required = true, paramType = "path")})
	@RequestMapping(value = "/label/get/{id}")
	public ResultMessage<List<StoreGoodsLabelVO>> storeGoodsLabel(@NotNull @PathVariable String id) {
		return ResultUtil.data(storeGoodsLabelService.listByStoreId(id));
	}

	@ApiOperation(value = "申请店铺第一步-填写企业信息")
	@PutMapping(value = "/apply/first")
	public ResultMessage<Object> applyFirstStep(StoreCompanyDTO storeCompanyDTO) {
		storeService.applyFirstStep(storeCompanyDTO);
		return ResultUtil.success();
	}

	@ApiOperation(value = "申请店铺第二步-填写银行信息")
	@PutMapping(value = "/apply/second")
	public ResultMessage<Object> applyFirstStep(StoreBankDTO storeBankDTO) {
		storeService.applySecondStep(storeBankDTO);
		return ResultUtil.success();
	}

	@ApiOperation(value = "申请店铺第三步-填写其他信息")
	@PutMapping(value = "/apply/third")
	public ResultMessage<Object> applyFirstStep(StoreOtherInfoDTO storeOtherInfoDTO) {
		storeService.applyThirdStep(storeOtherInfoDTO);
		return ResultUtil.success();
	}

	@ApiOperation(value = "获取当前登录会员的店铺信息-入驻店铺")
	@RequestMapping(value = "/apply")
	public ResultMessage<StoreDetailVO> apply() {
		return ResultUtil.data(storeDetailService.getStoreDetailVOByMemberId(UserContext.getCurrentUser().getId()));
	}

	@ApiOperation(value = "商家入驻申请")
	@PutMapping(value = "/applyBuyer")
	public ResultMessage<Store> applyBuyer(AdminStoreApplyDTO adminStoreApplyDTO) {
		adminStoreApplyDTO.setMemberId(UserContext.getCurrentUser().getId());
		return ResultUtil.data(storeService.add(adminStoreApplyDTO));
	}

	@RequestMapping("/getStoreStatus")
	@ApiOperation(value = "获取商家审核状态")
	public ResultMessage<JSONObject> getStoreStatus() {
		Store storeByMember = storeService.getStoreByMember();

		JSONObject json = new JSONObject();
		if (storeByMember == null) {
			json.put("storeByMember", null);
		} else {
			json.put("storeByMember", storeByMember.getStoreDisable());
			if (storeByMember.getCauser() == null || storeByMember.getCauser().equals("")) {
				json.put("causer", "");
			} else {
				json.put("causer", storeByMember.getCauser());
			}
		}

		// return ResultUtil.data(storeByMember == null ? null :
		// storeByMember.getStoreDisable());
		return ResultUtil.data(json);
	}

	@RequestMapping("/getStoreFeeStatus")
	@ApiOperation(value = "获取商家年费缴纳状态")
	public ResultMessage<Boolean> getStoreFeeStatus() {
		GradeLevelVO gradeLevel = storeService.findGradeLevel(UserContext.getCurrentUser().getId());
		return ResultUtil.data(gradeLevel == null ? false : true);
	}

	@ApiOperation(value = "查询订单列表")
	@RequestMapping(value = "/orderList")
	public ResultMessage<IPage<OrderSimpleVO>> queryMineOrder(OrderSearchParams orderSearchParams) {
		return ResultUtil.data(orderService.queryByParams(orderSearchParams));
	}

	@RequestMapping(value = "/getList")
	@ApiOperation(value = "获取店铺今日收益总额")
	public ResultMessage<Map<String, Object>> getList() {
		Map<String, Object> map = new HashMap<>();
		// PageVO pageVO = new PageVO();
		// pageVO.setPageSize(999999);
		// AuthUser authUser = UserContext.getCurrentUser();
		Double income = 0D;
		Double incomeAll = 0D;
		// QueryWrapper<WalletDetailVO> queryWrapper =new QueryWrapper<>();
		// queryWrapper.like("d.payee",authUser.getId());
		// queryWrapper.eq("d.transaction_type",
		// DepositServiceTypeEnum.WALLET_PAY.name());
		// queryWrapper.eq("d.payee_owner", WalletOwnerEnum.SALE.name());
		// IPage<WalletDetailVO> list =
		// walletDetailService.getIncomeList(pageVO,queryWrapper);
		// if(CollectionUtils.isNotEmpty(list.getRecords())){
		// //获取当前日期
		// Date d = new Date();
		// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		// for(WalletDetailVO walletDetail : list.getRecords()){
		// if(sdf.format(d).equals(sdf.format(walletDetail.getCreateTime()))) {
		// income = CurrencyUtil.add(income, walletDetail.getMoney());
		// }
		// incomeAll = CurrencyUtil.add(incomeAll,walletDetail.getMoney());
		// }
		// }
		QueryWrapper<Order> wrapper = new QueryWrapper<>();
		Member member = memberService.getUserInfo();
		wrapper.eq("store_id", member.getStoreId());
		wrapper.notIn("order_type", OrderTypeEnum.OFFLINE.name());
		wrapper.groupBy("id");
		wrapper.orderByDesc("create_time");
		List<Order> list = orderService.list(wrapper);
		if (CollectionUtils.isNotEmpty(list)) {
			for (Order order : list) {
				if (!order.getOrderStatus().equals(OrderStatusEnum.CANCELLED.name())
						&& !order.getOrderStatus().equals(OrderStatusEnum.UNPAID.name())) {
					// 获取当前日期
					Date d = new Date();
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					if (sdf.format(d).equals(sdf.format(order.getCreateTime()))) {
						income = CurrencyUtil.add(income, CurrencyUtil.sub(order.getFlowPrice(),
								order.getCommission() != null ? order.getCommission() : 0D));
					}
					incomeAll = CurrencyUtil.add(incomeAll, CurrencyUtil.sub(order.getFlowPrice(),
							order.getCommission() != null ? order.getCommission() : 0D));
				}
			}
		}
		map.put("income", income);
		map.put("incomeAll", incomeAll);
		return ResultUtil.data(map);
	}

	@ApiOperation(value = "获取商家已选择物流公司列表")
	@RequestMapping("/getChecked")
	public ResultMessage<List<StoreLogisticsVO>> getChecked() {
		String storeId = Objects.requireNonNull(UserContext.getCurrentUser()).getStoreId();
		return ResultUtil.data(storeLogisticsService.getStoreSelectedLogistics(storeId));
	}

	@ApiOperation(value = "订单发货")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "orderSn", value = "订单sn", required = true, dataType = "String", paramType = "path"),
			@ApiImplicitParam(name = "logisticsNo", value = "发货单号", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "logisticsId", value = "物流公司", required = true, dataType = "String", paramType = "query")})
	@RequestMapping(value = "/{orderSn}/delivery")
	public ResultMessage<Object> delivery(@NotNull(message = "参数非法") @PathVariable String orderSn, String logisticsNo,
			String logisticsId) {
		return ResultUtil.data(orderService.delivery(orderSn, logisticsNo, logisticsId));
	}

	@ApiOperation(value = "添加店铺评价")
	@RequestMapping("/addStoreEvaluation")
	public ResultMessage<StoreEvaluationDTO> addStoreEvaluation(StoreEvaluationDTO storeEvaluationDTO) {
		String orderNo = storeEvaluationDTO.getOrderNo();
		OrderVO bySn = orderService.getBySn(orderNo);
		storeEvaluationDTO.setStoreName(bySn.getStoreName());
		storeEvaluationDTO.setStoreId(bySn.getStoreId());
		return ResultUtil.data(storeEvaluationService.addStoreEvaluation(storeEvaluationDTO));
	}

	@ApiOperation(value = "根据店铺id查询同品类其他店铺")
	@RequestMapping("/getStoreListByPage")
	public ResultMessage<IPage<StoreVO>> getStoreListByPage(StoreSearchParams entity, PageVO page) {
		return ResultUtil.data(storeService.getStoreListByPage(entity, page));
	}

	// 营业执照识别
	@RequestMapping("/getBusinessLicense")
	public ResultMessage<StoreOtherVO> getBusinessLicense(@RequestParam("url") String url) throws Exception {
		StoreOtherVO storeOtherVO = new StoreOtherVO();
		com.aliyun.ocr20191230.Client client = OcrBusinessLicense.createClient("LTAI5tSbyR61qsScm433YW5g",
				"lwXmSW6XqwHhOiZ18rQaMPPoD1civM");
		RecognizeBusinessLicenseRequest recognizeBusinessLicenseRequest = new RecognizeBusinessLicenseRequest()
				.setImageURL(url);
		RuntimeOptions runtime = new RuntimeOptions();
		try {
			// 复制代码运行请自行打印 API 的返回值
			RecognizeBusinessLicenseResponse response = client
					.recognizeBusinessLicenseWithOptions(recognizeBusinessLicenseRequest, runtime);
			storeOtherVO.setCompanyName(response.getBody().getData().getName());
			storeOtherVO.setScope(response.getBody().getData().getBusiness());
			storeOtherVO.setLicenseNum(response.getBody().getData().getRegisterNumber());
			return ResultUtil.data(storeOtherVO);
		} catch (TeaException error) {
			// 如有需要，请打印 error
			com.aliyun.teautil.Common.assertAsString(error.message);
			System.out.println("营业执照识别失败：" + error.message);
		} catch (Exception _error) {
			TeaException error = new TeaException(_error.getMessage(), _error);
			// 如有需要，请打印 error
			com.aliyun.teautil.Common.assertAsString(error.message);
			System.out.println("营业执照识别失败：" + error.message);
		}
		return ResultUtil.error(ResultCode.BUSINESS_LICENSE_ERROR);
	}
}
